const { pool } = require('../config/db');

class UserModel {
  // 创建用户表
  static async createTable() {
    const sql = `
      CREATE TABLE IF NOT EXISTS users (
        id INT AUTO_INCREMENT PRIMARY KEY,
        openid VARCHAR(100) UNIQUE NOT NULL,
        nickname VARCHAR(100),
        avatar_url VARCHAR(500),
        gender TINYINT,
        phone VARCHAR(20),
        created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
        updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP
      )
    `;
    
    try {
      await pool.execute(sql);
      console.log('用户表创建成功');
    } catch (error) {
      console.error('创建用户表失败:', error);
      throw error;
    }
  }

  // 创建新用户
  static async create(userData) {
    const { openid, ...userInfo } = userData;
    const sql = `
      INSERT INTO users (openid, nickname, avatar_url, gender, phone)
      VALUES (?, ?, ?, ?, ?)
    `;
    
    try {
      const [result] = await pool.execute(sql, [
        openid,
        userInfo.nickname || null,
        userInfo.avatarUrl || null,
        userInfo.gender || null,
        userInfo.phone || null
      ]);
      
      return { id: result.insertId, openid, ...userInfo };
    } catch (error) {
      console.error('创建用户失败:', error);
      throw error;
    }
  }

  // 根据openid查找用户
  static async findByOpenid(openid) {
    const sql = 'SELECT * FROM users WHERE openid = ?';
    
    try {
      const [rows] = await pool.execute(sql, [openid]);
      return rows[0] || null;
    } catch (error) {
      console.error('查找用户失败:', error);
      throw error;
    }
  }

  // 更新用户信息
  static async update(openid, updateData) {
    const fields = Object.keys(updateData)
      .filter(key => key !== 'openid' && key !== 'id')
      .map(key => `${key} = ?`);
    
    const values = Object.values(updateData)
      .filter(value => value !== undefined);
    
    const sql = `
      UPDATE users 
      SET ${fields.join(', ')}
      WHERE openid = ?
    `;
    
    try {
      await pool.execute(sql, [...values, openid]);
      return this.findByOpenid(openid);
    } catch (error) {
      console.error('更新用户失败:', error);
      throw error;
    }
  }
}

module.exports = UserModel; 